//////////////////////////////////////////////////////////////////////////////////////////////////
// Global Variable
var gSessionId;
var gCustomerInfo;
var gClaimInfoList;
var gClaimDetail;
var gCapturePhotoUrl = "images/captureimage.png";
var gLatitude;
var gLongitude;
var gLocation;
var gAccImageUrl;
var gCurrentClaimId;
var markers;
var map;

// ///////////////////////////////////////////////////////////////////////////////////////////////

function wlCommonInit() {

	/*
	 * Application is started in offline mode as defined by a connectOnStartup
	 * property in initOptions.js file. In order to begin communicating with
	 * Worklight Server you need to either:
	 * 
	 * 1. Change connectOnStartup property in initOptions.js to true. This will
	 * make Worklight framework automatically attempt to connect to Worklight
	 * Server as a part of application start-up. Keep in mind - this may
	 * increase application start-up time.
	 * 
	 * 2. Use WL.Client.connect() API once connectivity to a Worklight Server is
	 * required. This API needs to be called only once, before any other
	 * WL.Client methods that communicate with the Worklight Server. Don't
	 * forget to specify and implement onSuccess and onFailure callback
	 * functions for WL.Client.connect(), e.g:
	 * 
	 * WL.Client.connect({ onSuccess: onConnectSuccess, onFailure:
	 * onConnectFailure });
	 * 
	 */
	// initialization code for button click
	console.log('-wlCommonInit : Start up');
	$('#loginBtn').bind('click', callAuthenCustomer); // call Adapter when
														// clicked
	$('#takePhotoBtn').bind('click', takePhoto); // call to take photo
	$('#syncBtn').bind('click', callGetAllClaimInfoForCustomer); // call to
																	// take
																	// photo
	$(document).on("click", ".claimInfoItem", function() {
		viewClaimDetail($(this).attr("id"));
	});

	$('#sendRequest').bind('click', uploadPhoto); // call to send claim
													// request
	$('#cancelRequest').bind('click', cancelClaimRequest); // call to send
															// claim request
	
	$('#surveyorTelephoeBtn').bind('click', makeSurveyorCall);
	if (WL.Client.Push){
	  	
	  	WL.Client.Push.onReadyToSubscribe = function(){
	  		//alert("onReadyToSubscribe");
	  		WL.Client.Push.registerEventSourceCallback(
	  				"MyPush", 
	  				"PushAdapter", 
	  				"PushEventSource", 
	  				MyPushPushNotificationReceived);

	  		WL.Client.Push.registerEventSourceCallback(
	  				"MapPush", 
	  				"PushAdapter", 
	  				"PushEventSource", 
	  				MapPushPushNotificationReceived);
	  		
	  		WL.Client.Push.registerEventSourceCallback(
	  				"UpdateJob", 
	  				"PushAdapter", 
	  				"PushEventSource", 
	  				UpdateJobPushNotificationReceived);

	  	};
	  	
	  }
	
		getCurrentLocationMap();

		$('#LocationBtn').bind('click',function(){
			 
			$.mobile.changePage("#map-page", {transition: "none"});
		});
}

// initialization code for opening page
// 1. customerInfoPage
$(document).on(
		'pagebeforeshow',
		'#customerInfoPage',
		function(event) {
			console.log(' customerInfoPage - pagebeforeshow');
			$('#carImageInfo').attr('src', gCustomerInfo.CarImg);
			//$('#carImageInfo').src = gCustomerInfo.CarImg;
			$('#licenseplateInfo').val(gCustomerInfo.LicensePlate);
			$('#nameInfo')
					.val(gCustomerInfo.Name + " " + gCustomerInfo.Surname);
			$('#cardetailInfo').val(
					gCustomerInfo.CarBrand + " " + gCustomerInfo.CarModel + " "
							+ gCustomerInfo.CarColor);
			$('#mobileInfo').val(gCustomerInfo.Mobile);
		});

// 2. claimRequestPage
$(document).on(
		'pagebeforeshow',
		'#claimRequestPage',
		function(event) {
			console.log(' claimRequestPage - pagebeforeshow');
			$('#licenseplateRequest').val(gCustomerInfo.LicensePlate);
			$('#nameRequest').val(
					gCustomerInfo.Name + " " + gCustomerInfo.Surname);
			$('#cardetailRequest').val(
					gCustomerInfo.CarBrand + " " + gCustomerInfo.CarModel + " "
							+ gCustomerInfo.CarColor);
			$('#mobileRequest').val(gCustomerInfo.Mobile);
		});

// 3. claimListPage
$(document).on('pagebeforeshow', '#claimListPage', function(event) {
	console.log(' claimListPage - pagebeforeshow');

	//if (typeof (gClaimInfoList) == 'undefined' || gClaimInfoList == null) {
		// call adapter to load data
		callGetAllClaimInfoForCustomer();
	//} else {
	//	refreshClaimListView();
	//}
});

// 4. claimDetailPage
$(document).on('pagebeforeshow', '#claimDetailPage', function(event) {
	console.log(' claimDetailPage - pagebeforeshow');
	
	var dateStr = getFormatJsonDate(gClaimDetail.AccDate);
	var statusStr = getClaimStatus(gClaimDetail.Status);
	
	$('#surveyorImageDetail').attr('src', (gClaimDetail.SurvImg == '' ? '' : 'http://202.21.149.53/DroidClaim/images/'+gClaimDetail.SurvImg));
	$('#surveyorImageDetail').src = (gClaimDetail.SurvImg == '' ? '' : 'http://202.21.149.53/DroidClaim/images/'+gClaimDetail.SurvImg);
	$('#claimidDetail').val(gClaimDetail.Id);
	$('#locationDetail').val(gClaimDetail.AccidentLocation);
	$('#dateDetail').val(dateStr);
	$('#surveyornameDetail').val(gClaimDetail.SurvName);
	$('#surveyormobileDetail').val(gClaimDetail.SurvMobile);
	$('#statusDetail').val(statusStr);
	
	if(gClaimDetail.Status>=4){
		$('#LocationBtn').hide();
	}else{
		$('#LocationBtn').show();
	}
});

//5. claimMapPage
$(document).on('pageshow', '[data-role="page"]#map-page', function(event) {
	console.log(' map-page - pagebeforeshow');

	var iconAccident = new google.maps.MarkerImage("images/accident.png");
	 markers = [
	               {
	                   "title": 'Accident',
	                   "lat": gLatitude,
	                   "lng": gLongitude,
	                   "description": 'Accident',
	                   icon: iconAccident
	               }
	       ];

		wlMapDrawPolyline(markers);

        google.maps.event.trigger(map, 'resize');
});
// match(/\d+/)[0] * 1)
// ///////////////////////////////////////////////////////////////////////////////////////////////
// Adapter Handler
// ///////////////////////////////////////////////////////////////////////////////////////////////

function makeSurveyorCall() {
	console.log(' makeCall - begin');
	//window.open("tel:" + gClaimDetail.CustMobile);
	// window.open("tel:0858056696"); iOS
	window.open('tel:'+ gClaimDetail.SurvMobile, '_system', 'location=yes');
	console.log(' makeCall - end');
}

// ///////////////////////////////////////////////////////////////////////////////////////////////
// 1. AuthenCustomer
function callAuthenCustomer() {
	$.mobile.showPageLoadingMsg();
	console.log('-callAuthenCustomer : begin');

	var licensePlate = $('#licensePlateInp').val();
	var password = $('#passwordInp').val();
	if (!licensePlate || licensePlate.length === 0 || !password || password.lenght === 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty license plate or password");
		/*navigator.notification.alert('empty license plate or password!', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}

	var authenCustomerDto = new Object();
	authenCustomerDto.LicensePlate = licensePlate;
	authenCustomerDto.Password = password;
	authenCustomerDto.RegistrationId = "APA91bHY6wIT6x7v1Q_d3ByHbMuyF8mC5q9GGvb24ow3dBw3DHnAq4NK7Q7X0INtZA2CJt0IolVUBlf0M29PlKXTHpOkQnUpbrn8pJ8vQBMtNm5f7h3QnhqDVQ4VQwfy6M02OoTSS7SYjXZ2RMaukE9hIchZvsxU4A";

	var callSuccess = function(result) {
		subscribe();
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callAuthenCustomer : Success');

		if (!invocationResult.Result) {
			alert("Invalid username or password");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		//alert(invocationResult.SessionId);

		// keep data to global space
		gSessionId = invocationResult.SessionId;
		gCustomerInfo = invocationResult.CustomerInfo;
		
		//$('#map-page').hide();
		$.mobile.changePage("#customerInfoPage", {transition: "none"});
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callAuthenCustomer : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'AuthenCustomer',
		parameters : [ authenCustomerDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 2. GetAllClaimInfoForCustomer
function callGetAllClaimInfoForCustomer() {
	$.mobile.showPageLoadingMsg();
	console.log('-callGetAllClaimInfoForCustomer : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		// alert("Error : empty session id");
		navigator.notification.alert('empty session id', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);
		return;
	}
	// alert(gSessionId);
	var sessionPkDto = new Object();
	sessionPkDto.SessionId = gSessionId;

	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callGetAllClaimInfoForCustomer : Success');

		if (!invocationResult.Result) {
			alert("Error : call not success");
			navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);
			return;
		}
		// keep data to global space
		gClaimInfoList = invocationResult.ClaimInfoList;
		refreshClaimListView();

		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callGetAllClaimInfoForCustomer : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'GetAllClaimInfoForCustomer',
		parameters : [ sessionPkDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

// ///////////////////////////////////////////////////////////////////////////////////////////////
// 3. callAddClaimRequest
function callAddClaimRequest() {
	$.mobile.showPageLoadingMsg();
	console.log('-callAddClaimRequest : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		// alert("Error : empty session id");
		navigator.notification.alert('empty session id', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);
		return;
	}

	var claimRequestDto = new Object();
	claimRequestDto.SessionId = gSessionId;
	claimRequestDto.AccImg = gAccImageUrl;
	claimRequestDto.Latitude = gLatitude;
	claimRequestDto.Longitude = gLongitude;
	claimRequestDto.Location = gLocation;

	var callSuccess = function(result) {
		//$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callAddClaimRequest : Success');

		if (!invocationResult.Result) {
			alert("Invalid username or password");
			navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);
			return;
		}
		//alert(invocationResult.SessionId);
		
		// keep data to global space
		gCurrentClaimId = invocationResult.ClaimInfoId;
		//$.mobile.changePage("#customerInfoPage", "flip", false, false);
		callGetClaimInfoForCustomer();
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callAddClaimRequest : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'AddClaimRequest',
		parameters : [ claimRequestDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 4. callgetLocation
function callGetLocation(){
	if (typeof(gLatitude)  == 'undefined' || gLatitude  == null ||
		typeof(gLongitude) == 'undefined' || gLongitude == null ){
		return;  
	}
		
	// Called when the adapter completes successfully 
	var onGetLocationSuccess = function(result){
		var globalAddress = result.invocationResult.results[0].formatted_address;
		// alert('globalAddress[' + globalAddress.length + '] '+ globalAddress);
		if(globalAddress.length == 0){
			alert("call GetLocation result fail");
			return;
		}
		gLocation = globalAddress;
		callAddClaimRequest();
		return;
	};

	// Called when the adapter does NOT complete successfully 
	var onGetLocationFail = function(){
		alert("call GetLocation fail");
		console.log('-callGetLocation:lose - Failed to obtain address for GPS');		
		$.mobile.hidePageLoadingMsg();

		return;
	};
	
	var invocationData = {
			adapter    : 'GoogleMapBL',
		    procedure  : 'getLocation',
		    parameters : [gLatitude, gLongitude]
	};
	
	var options = {
		onSuccess : onGetLocationSuccess,
		onFailure : onGetLocationFail
	};
	
	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 5. GetClaimInfoForCustomer
function callGetClaimInfoForCustomer() {
//	$.mobile.showPageLoadingMsg();
	console.log('-callGetClaimInfoForCustomer : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty license plate or password!', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	// alert(gSessionId);
	var claimInfoPKDto = new Object();
	claimInfoPKDto.SessionId = gSessionId;
	claimInfoPKDto.Id = gCurrentClaimId;
	
	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callGetClaimInfoForCustomer : Success');
		if (!invocationResult.LicensePlate || invocationResult.LicensePlate.length<=0) {
			alert("Error : call callGetClaimInfoForCustomer result not success");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		// keep data to global space
		//gClaimInfoList = invocationResult.ClaimInfoList;
		//refreshClaimListView();
		gClaimDetail = new Object();
		gClaimDetail.Id = gCurrentClaimId;
		gClaimDetail.AccidentLocation = gLocation;
		gClaimDetail.Latitude = gLatitude;
		gClaimDetail.Longitude = gLongitude;
		gClaimDetail.Status = invocationResult.Status;
		gClaimDetail.LicensePlateNo = invocationResult.LicensePlate;
		gClaimDetail.SurvName = invocationResult.SurveyorName;
		gClaimDetail.SurvMobile = invocationResult.SurveyorMobile;
		gClaimDetail.SurvImg = invocationResult.SurveyorImg;
		
		gClaimDetail.AccDate = JSON.stringify(new Date()); 
		var dateStr = getFormatJsonDate(gClaimDetail.AccDate);
		var statusStr = getClaimStatus(gClaimDetail.Status);
		
		$('#surveyorImageDetail').attr('src', gClaimDetail.SurvImg);
		$('#surveyorImageDetail').src = gClaimDetail.SurvImg;
		$('#claimidDetail').val(gClaimDetail.Id);
		$('#locationDetail').val(gClaimDetail.AccidentLocation);
		$('#dateDetail').val(dateStr);
		$('#surveyornameDetail').val(gClaimDetail.SurvName);
		$('#surveyormobileDetail').val(gClaimDetail.SurvMobile);
		$('#statusDetail').val(statusStr);
		
		if(gClaimDetail.Status>=4){
			$('#LocationBtn').hide();
		}else{
			$('#LocationBtn').show();
		}
		
		//$('#map-page').hide();
		$.mobile.changePage("#claimDetailPage", {transition: "none"});
		
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callGetClaimInfoForCustomer : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'GetClaimInfoForCustomer',
		parameters : [ claimInfoPKDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
//
function refreshClaimListView() {
	if (typeof (gClaimInfoList) == 'undefined' || gClaimInfoList == null) {
		// do nothing
		return;
	}
	
	$("#claimInfoListView").empty();
	var data = gClaimInfoList;
	var numItem = data.length;
	/*if(numItem>5){
		numItem = 5;
	}

	$('#claimInfoListView').empty();
	for (var i = 0; i < numItem; i++) {
		var item = data[i];
		// var date = new Date(parseInt(item.AccDate.match(/(\d+)/)[1],10));
		// var dateStr = date.format("m/dd/yy h:MM");
		var listItem = $('<li>'
				+ '<a data-rel=\'dialog\' class="claimInfoItem" id="' + i
				+ '">' + '<img style=\'margin: 10px\' src=\'' + item.SurvImg
				+ '\'  width="60px"/>' + '<h6>' + item.AccidentLocation
				+ '</h6>' + '<p>Date :' + item.AccDate + '</p>' + '<p>Status :'
				+ item.Status + '</p>' + '</a>' +
				// '<a href=\'#\' data-rel=\'dialog\'></a>'+
				'</li>');
		$("#claimInfoListView").append(listItem);
	}*/
	
	for (var i = 0; i < 5; i++) {
		var item = data[numItem-1-i];
		//var date = new Date(parseInt(item.AccDate.slice(6, -2)));
		//var dateStr;
		//dateStr = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
		//dateStr = dateStr + " " + date.getHours() + ":" + date.getMinutes();
		var dateStr = getFormatJsonDate(item.AccDate);
		var statusStr = getClaimStatus(item.Status);
		// alert(dateStr);
		// var date = new Date(parseInt(item.AccDate.match(/(\d+)/)[1],10));
		// var dateStr = date.format("m/dd/yy h:MM");
		var listItem = $('<li>'
				+ '<a data-rel=\'dialog\' class="claimInfoItem" id="' + i
				+ '">' + '<img style=\'margin: 10px\' src=\'' + (item.SurvImg == '' ? '' : 'http://202.21.149.53/DroidClaim/images/'+item.SurvImg)
				+ '\'  width="60px"/>' + '<h6>' + item.AccidentLocation
				+ '</h6>' + '<p>Date :' + dateStr + '</p>' + '<p>Status : '
				+ statusStr + '</p>' + '</a>' +
				// '<a href=\'#\' data-rel=\'dialog\'></a>'+
				'</li>');
		$("#claimInfoListView").append(listItem);
	}

	$('#claimInfoListView:visible').listview('refresh');
}

// ////////////////////////////////////////////////////////////////////////////////////////////////
// 
function viewClaimDetail(id) {
	if (typeof (gClaimInfoList) != 'undefined' && gClaimInfoList != null) {
		
		var itemNo = gClaimInfoList.length-1-id;
		
		gClaimDetail = gClaimInfoList[itemNo];
		//$('#map-page').hide();
		$.mobile.changePage("#claimDetailPage", {transition: "none"});
	}
}

// /////////////////////////////////////////////////////////////////////////////////////////////////
// send calim request page
function cancelClaimRequest() {
	var image = $('#captareImageRequest');
	image.attr('src', 'images/captureimage.png');
	image.src = imageData;
	// image.src = image;
	image.show();
}

function takePhoto() {
	console.log("in capturePhoto()");
	// Take picture using device camera and retrieve image as base64-encoded
	// string
	// navigator.camera.getPicture(onTakePhotoSuccess, onFail, {
	// quality : 10,
	// destinationType : navigator.camera.DestinationType.DATA_URL
	// });

	navigator.camera.getPicture(onTakePhotoSuccess, onTakePhotoFail, {
		quality : 50,
		destinationType : Camera.DestinationType.FILE_URI
	});
}

// success callBack.
function onTakePhotoSuccess(imageData) {
	console.log("in onPhotoDataSuccess()");

	var image = $('#captareImageRequest');
	// $('#captareImageImg').attr('src', "data:image/jpeg;base64," + imageData);
	// image.src = "data:image/jpeg;base64," + imageData;
	image.attr('src', imageData);

	//image.src = imageData;
	gCapturePhotoUrl = imageData;
	// image.src = image;
	image.show();

}

// failed callBack.
function onTakePhotoFail(message) {
	console.log("in onFail() - " + message);
	alert('take photo failed : ' + message);
}

function uploadPhoto() {
	imageURI = gCapturePhotoUrl;
	
	var options = new FileUploadOptions();
	options.fileKey = "file";
	options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
	options.mimeType = "image/jpeg";

	var params = new Object();
	params.value1 = "test";
	params.value2 = "param";

	options.params = params;
	var ft = new FileTransfer();
	ft.upload(imageURI, "http://202.21.149.53/DroidClaim/UploadFile.ashx",
			onUploadSuccess, onUploadFail, options);
}

function onUploadSuccess(result) {
	var r = JSON.parse(result.response);
	
	if (!r.Result) {
		$.mobile.hidePageLoadingMsg();
		alert('Error : result from call upload is not OK');
		return;
	}

	gAccImageUrl = r.ListFiles[0];
	getCurrentLocation();
}

function onUploadFail(error) {
	$.mobile.hidePageLoadingMsg();
	alert("An error has occurred: Code = " + error.code);
	console.log("upload error source " + error.source);
	console.log("upload error target " + error.target);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////
// Location
function getCurrentLocation() {

	var onLocationSuccess = function(position) {
		console.log('-getCurrentLocation : Success');
		gLatitude = position.coords.latitude;
		gLongitude = position.coords.longitude;
		callGetLocation();
		return;
	};

	var onLocationError = function(error) {
		$.mobile.hidePageLoadingMsg();
		alert('Error Code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
		console.log('-getCurrentLocation : Failed');
		return;
	};
	 
	navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError,{
	      enableHighAccuracy : true
	 });
}

///////////////////////////////////////////////////////////////////////////////////
// Utility
function getFormatJsonDate(jsonDate){
	if (typeof(jsonDate)  == 'undefined' || jsonDate  == null){
		return "";  
	}
	var date = new Date(parseInt(jsonDate.slice(6, -2)));
	var dateStr;
	dateStr = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
	dateStr = dateStr + " " + date.getHours() + ":" + date.getMinutes();
	
	return dateStr;
}

function getClaimStatus(code){
	var status = '';
	if(code===1){
		status = 'Claim Started';
	}else if(code===2){
		status = 'Claim Received';
	}else if(code===3){
		status = 'Surveyor Accepted';
	}else if(code===4){
		status = 'Job Handled';
	}else if(code===5){
		status = 'Got ClaimDoc Id';
	}

	return status;
}
////////////////////////////////////////////////////////////////////////////////////
function subscribe(){
	WL.Client.Push.subscribe("MyPush", {
		onSuccess: pushSubscribe_Callback,
		onFailure: pushSubscribe_Callback
	});

	WL.Client.Push.subscribe("UpdateJob", {
		onSuccess: pushSubscribe_Callback,
		onFailure: pushSubscribe_Callback
	});
	WL.Client.Push.subscribe("MapPush", {
		onSuccess: pushSubscribe_Callback,
		onFailure: pushSubscribe_Callback
	});

	getCurrentLocationMap();
}

function pushSubscribe_Callback(response){
	//alert("PushSubscribe_Callback invoked");
}

//------------------------------- Handle received notification ---------------------------------------
function MyPushPushNotificationReceived(props, payload){
	//alert("MyPushPushNotificationReceived invoked");
	alert("Job has been assigned.");
	gCurrentClaimId = payload.id;
	callGetClaimInfoForCustomer();
}
function UpdateJobPushNotificationReceived(props, payload){
	alert("Job is completed.");
	gCurrentClaimId = payload.id;
	callGetClaimInfoForCustomer();
}
function MapPushPushNotificationReceived(props, payload){

	var iconAccident = new google.maps.MarkerImage("images/accident.png");
	var iconSurveyor = new google.maps.MarkerImage("images/motorcycle.png");
	 markers = [
					{
					    "title": 'Surveyor',
					    "lat": payload.lat,
					    "lng": payload.lng,
					    "description": 'Surveyor',
					    icon: iconSurveyor
					}
		           , 
		           {
	                   "title": 'Accident',
	                   "lat": gLatitude,
	                   "lng": gLongitude,
	                   "description": 'Accident',
		               icon: iconAccident
	               }
	               
	       ];
	 wlMapDrawPolyline(markers);
}

function wlMapDrawPolyline(markers){
	var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();
        for (var i = 0; i < markers.length; i++) {
            var data = markers[i];
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            lat_lng.push(myLatlng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title,
                icon: data.icon
            });

            latlngbounds.extend(marker.position);

            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);

        }

        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);
        //alert(markers.length);
        if(markers.length < 2)
        	return;
        
        
        //***********ROUTING****************//

        //Intialize the Path Array

        var path = new google.maps.MVCArray();

        //Intialize the Direction Service

        var service = new google.maps.DirectionsService();

        //Set the Path Stroke Color

        var poly = new google.maps.Polyline({ map: map, strokeColor: '#e74976' });

        //Loop and Draw Path Route between the Points on MAP

        for (var i = 0; i < lat_lng.length; i++) {
            if ((i + 1) < lat_lng.length) {
                var src = lat_lng[i];
                var des = lat_lng[i + 1];
                path.push(src);
                poly.setPath(path);
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                            path.push(result.routes[0].overview_path[i]);
                        }
                    }
                });
            }
        }	
}

function getCurrentLocationMap() {

	var onLocationSuccess = function(position) {
		console.log('-getCurrentLocation : Success');
		gLatitude = position.coords.latitude;
		gLongitude = position.coords.longitude;
		return;
	};

	var onLocationError = function(error) {
		$.mobile.hidePageLoadingMsg();
		//* alert('Error Code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
		console.log('-getCurrentLocation : Failed');
		return;
	};
	 
	navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError,{
	      enableHighAccuracy : true
	 });
}